package com.wjh.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wjh.common.Constants;
import com.wjh.util.RedisUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 登录检查
 * 
 * @author wenjianhai
 * @date 2023/6/22
 * @since JDK 17
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

	private RedisUtils redisUtils;

	public LoginInterceptor() {
	}

	public LoginInterceptor(RedisUtils redisUtils) {
		this.redisUtils = redisUtils;
	}

	/**
	 * 目标方法执行之前
	 * <p>
	 * 登录检查写在这里，如果没有登录，就不执行目标方法
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @return boolean
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader("TOKEN");

		if (StringUtils.isBlank(token)) {
			log.info("登录拦截器,请求头中的token为空");
			throw new RuntimeException("请求头中的token为空");
		}
		token = Constants.LOGIN_TOKEN + token;

		Object obj = redisUtils.getObj(token);

		if (obj == null) {
			log.info("登录拦截器,用户尚未登录.token:{}", token);
			throw new RuntimeException("您没有权限进行此操作，请先登录！");
		}
		return true;
	}

	/**
	 * 目标方法执行完成以后
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 页面渲染以后
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}
